﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Krile.Kernel.Control.Surface.MessageObjects;
using Krile.Kernel.Control;
using System.Text.RegularExpressions;
using Krile.Kernel.Control.Surface;

namespace Mixture.Common
{
    public static class XStringGenerator
    {
        public static XString CreateXString(this string text, string replyToId)
        {
            XString xs = new Krile.Kernel.Control.XString();
            xs.Original = text;
            if (!String.IsNullOrEmpty(replyToId))
                xs.HeaderText = ">>" + replyToId;
            xs.MessageObjects = CreateMsgObjects(text);
            return xs;
        }

        static MessageObject[] CreateMsgObjects(string msg)
        {
            msg = msg.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\r", "").Replace("\n", " ");
            //pre-processor
            msg = Krile.Common.Regexs.URLRegex.Replace(msg, "<$1>$1<");

            List<MessageObject> objStock = new List<MessageObject>();
            foreach (var item in msg.Split(new[] { '<' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (item.Contains('>'))
                {
                    var iArray = item.Split('>');
                    //link
                    string origstr = iArray[0].Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");

                    origstr = origstr.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&");
                    objStock.Add(new Hyperlink(origstr));
                    Image ig = null;
                    if (Kernel.Config.EmbeddingImage && (ig = GetImage(origstr)) != null)
                    {
                        objStock.Add(ig);
                    }
                    continue;
                }
                else
                    objStock.Add(new Text(item.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&")));
            }
            return objStock.ToArray();
        }

        private static Image GetImage(string url)
        {
            if (url.EndsWith(".png") ||
                url.EndsWith(".jpg") || url.EndsWith(".jpeg") || url.EndsWith(".jpe") ||
                url.EndsWith(".bmp") || url.EndsWith(".dib") ||
                url.EndsWith("gif"))
            {
                try
                {
                    return new Image(new Uri(url));
                }
                catch (UriFormatException)
                {
                    return null;
                }
            }
            return null;
        }
    }
}
